package com.example.wm.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.wm.common.ResultData;
import com.example.wm.entity.TencentCosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.example.wm.common.Result;
@RestController
@RequestMapping("/cos")
//上传腾讯云桶
public class CosController {

    @Autowired
    private TencentCosProperties tencentCosProperties;
    @CrossOrigin
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        if (ObjectUtils.isEmpty(file)) {
            return ResultData.error(1,"无文件") ;
        }
        UUID uuid  =  UUID.randomUUID();
        String s = UUID.randomUUID().toString();
        s = s.replace("-", "");
        int num = s.hashCode();
        num = num < 0 ? -num : num;
        s = String.valueOf(num);
        String filename = file.getOriginalFilename();
        //解码
        String originalFilename= URLDecoder.decode(filename);
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "")+".png";

        //1.初始化客户端
        COSClient cosClient = createCosClient();

        //2.上传文件
        File localFile = null;
        String bucket = tencentCosProperties.getBucket();
        try {
            localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);
            //指定文件上传到 COS 上的路径
            String key = "img/" + newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, localFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return ResultData.success("https://imges-1316837992.cos.ap-guangzhou.myqcloud.com/img/"+newFileName,newFileName);
        } catch (IOException e) {
            return ResultData.error(1,"上传失败") ;
        } finally {
            cosClient.shutdown();
        }
    }

    private COSClient createCosClient() {
        //1.1 初始化用户身份信息
        BasicCOSCredentials credentials = new BasicCOSCredentials(tencentCosProperties.getAccessKey(), tencentCosProperties.getSecretKey());
        //1.2 设置bucket的地域
        String reg=tencentCosProperties.getRegion();
        Region region=new Region(reg);
        ClientConfig clientConfig = new ClientConfig(region);
        //1.3 生成cos客户端
        COSClient cosClient = new COSClient(credentials, clientConfig);
        return cosClient;
    }


    @PostMapping("/download")
    public String download(@RequestParam("fileName") String fileName) {
        TransferManager transferManager = createTransferManager();

        String bucket = tencentCosProperties.getBucket();
        String key = "img/" + fileName;
        //下载到工程目录下的imgs文件夹中
        File downloadFile = new File(System.getProperty("user.dir") + "/imgs/"+fileName);

        GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key);
        try {
            //返回一个异步结果 Donload, 可同步的调用 waitForCompletion 等待下载结束, 成功返回 void, 失败抛出异常
            Download download = transferManager.download(getObjectRequest, downloadFile);
            download.waitForCompletion();
            return "下载文件成功";
        } catch (InterruptedException e) {
            return "下载文件失败";
        } finally {
            shutdownTransferManager(transferManager);
        }
    }
    @CrossOrigin
    @PostMapping("/delete")
    public String delete(@RequestBody JSONObject jsonObject){
        JSONObject file = jsonObject.getJSONObject("file");
          String filename=file.getString("name");
        COSClient cosClient = createCosClient();
        String bucket = tencentCosProperties.getBucket();
        String key = "img/" + filename;
        try {
            cosClient.deleteObject(bucket,key);
            return "删除文件成功";
        } catch (CosClientException e) {
            return "删除文件失败";
        } finally {
            cosClient.shutdown();
        }

    }


    private void shutdownTransferManager(TransferManager transferManager) {
        // 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
        // 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
        transferManager.shutdownNow(true);
    }

    private TransferManager createTransferManager() {
        //初始化客户端
        COSClient cosClient = createCosClient();
        //创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        //创建 TransferManager
        return new TransferManager(cosClient, threadPool);
    }

}
